package com.blustreaksw.cyclecoach.userManagment;

import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.MainActivity;
import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.UserManagementActivity;
import com.blustreaksw.cyclecoach.data.UserProfile;
import com.blustreaksw.cyclecoach.util.ConfirmationDialogFragment;

/***********************************************************************
 * Display creation and UI logic user selection list fragment.
 * 
 * @author Tomas Rivera
 *
 ***********************************************************************/
public class Fragment_List_SelectUser extends ListFragment {
	
	ArrayList<UserProfile.UserNameAndIdContainer> mUserList;
	
	private TextView mEmptyView;
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		setRetainInstance(true);
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.ListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.list_empty, parent, false);
		mEmptyView = (TextView)v.findViewById(R.id.emptyView);
		mEmptyView.setText("No users registered");
		getActivity().setTitle("Select User");
		
		mUserList = new ArrayList<UserProfile.UserNameAndIdContainer>();
		getUserProfileFromActivity().getUserList(mUserList);
		
		UserListAdapter userAdapter = new UserListAdapter(mUserList);
		setListAdapter(userAdapter);
		((UserListAdapter)getListAdapter()).notifyDataSetChanged();
		return v;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		
		UserProfile.UserNameAndIdContainer uc = ((UserListAdapter)getListAdapter()).getItem(position);
		
		// Go to the main menu screen.
		Intent i = new Intent(getActivity(), MainActivity.class);
		i.putExtra(MainActivity.EXTRA_USER_ID, uc.getUserId());
		startActivity(i);
    }
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.ListFragment#onViewCreated(android.view.View, android.os.Bundle)
	 */
	@Override
	public void onViewCreated(View v, Bundle savedInstanceState) {
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> av, View v, int position, long id) {
				
				final String userName = ((UserListAdapter)getListAdapter()).getItem(position).getUserName();
				final long userId = ((UserListAdapter)getListAdapter()).getItem(position).getUserId();
				new ConfirmationDialogFragment().configureDialog(new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Ok
						
						// purge database for user
						
						// delete user
						
						((UserListAdapter)getListAdapter()).notifyDataSetChanged();
					}
				}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Cancel
						
					}
				}, "Confirm deletion", "Are you sure you want to delete " + userName + "?\nAll workout data will be lost and cannot be recovered.", getActivity())
				.onCreateDialog(null).show();
				
				return true;
			}
			
		});
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {

    		case R.id.action_createUserWizard_newUser:
    			getUserProfileFromActivity().resetProfile();
    			
    			Fragment fragment;
    			if((fragment = getActivity().getSupportFragmentManager().
    					findFragmentByTag(UserManagementActivity.FRAGMENT_USER_PROFILE)) == null) {
    				fragment = new Fragment_Wizard_UserProfile();
    			}
    			
    			// Transition to the next fragment.
    			getActivity().getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragmentContainer, fragment, UserManagementActivity.FRAGMENT_USER_PROFILE)
					.addToBackStack(null)
					.commit();
    			return true;
    		
    		// All other buttons are hidden from the user.
    		case R.id.action_createUserWizard_restartDeviceScan:
    		case R.id.action_createUserWizard_cancelButton:   			
    		case R.id.action_createUserWizard_nextButton:
    		case R.id.action_createUserWizard_prevButton:
    		case R.id.action_createUserWizard_saveButton:
    		default:
    			return super.onOptionsItemSelected(item); 
    	}
    }
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onPrepareOptionsMenu(android.view.Menu)
	 */
	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		
		// Show only the newUser button.
		menu.findItem(R.id.action_createUserWizard_newUser).setVisible(true);
		
		// Hidden options
		menu.findItem(R.id.scanning_indicator).setActionView(R.layout.progress_indicator).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_restartDeviceScan).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_prevButton).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_nextButton).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_saveButton).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_cancelButton).setVisible(false);
	}

	/*
	 * Container for the clickable list of user profiles that can be 
	 * presented to the user to choose from.
	 */
	private class UserListAdapter extends ArrayAdapter<UserProfile.UserNameAndIdContainer> {
		
		public UserListAdapter(ArrayList<UserProfile.UserNameAndIdContainer> users) {
			super(getActivity(), 0, users);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_select_user_item, null);
			}
			
			UserProfile.UserNameAndIdContainer u = getItem(position);
			
			TextView userNameTextView = (TextView)convertView.findViewById(R.id.selectProfile_usernameTextView);
			userNameTextView.setText(u.getUserName());
			return convertView;
		}
	}
	
	/*
	 * Returns UserProfile object from hosting activity.
	 */
	private UserProfile getUserProfileFromActivity() { return ((UserManagementActivity)getActivity()).getUserProfile(); }
}
